package spring.chatroom.java_chatroom.server.imp;

import cn.hutool.core.lang.hash.Hash;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import spring.chatroom.java_chatroom.server.SavaFilesInterface;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.rmi.ServerException;
import java.sql.Time;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Slf4j
@Service
public class SavaFiles implements SavaFilesInterface {

    @Value("${file.local-pic-path}")
    private String localPicPath = "F:\\chat_files\\files";
    @Value("${file.local-video-path}")
    private String localVideoPath = "F:\\chat_files\\video";
    @Value("${file.local-video-path}")
    private String localDocPath = "F:\\chat_files\\document";

    private final Set<String> picSet = Set.of(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".svg", ".ico");

    private final Set<String> videoSet = Set.of(".mp4",    // MPEG-4 Part 14 (最通用)
            ".avi",    // Audio Video Interleave (古老但常见)
            ".mov",    // QuickTime File Format (Apple)
            ".wmv",    // Windows Media Video
            ".flv",    // Adobe Flash Video (逐渐淘汰)
            ".webm",   // 开放网络媒体格式 (常用于网页)
            ".mkv",    // Matroska Video (开放容器格式，支持多种编码)
            ".m4v",    // iTunes 视频格式
            ".mpg",    // MPEG-1 或 MPEG-2
            ".mpeg",   // MPEG-1 或 MPEG-2
            ".3gp",    // 3GPP 多媒体文件 (旧手机格式)
            ".mts",    // AVCHD 视频文件 (高清摄像机格式)
            ".ts",     // MPEG Transport Stream (常用于流媒体和数字广播)
            ".vob",    // DVD 视频对象
            ".rm",     // RealMedia (逐渐淘汰)
            ".rmvb"   // RealMedia Variable Bitrate);
    );
    private final Set<String> documentSet = Set.of(  ".doc", ".docx", ".pdf", ".rtf", ".txt", ".odt", ".wps", // 文字处理
            ".xls", ".xlsx", ".ods",  // 电子表格
            ".ppt", ".pptx", ".odp",  // 演示文稿
            ".zip", ".rar", ".7z",  // 压缩文件
            ".html", ".htm", ".css", ".xml",  // 网页文件
            ".csv", ".json", ".js", ".py", ".java", ".cpp",  // 文本与代码
            ".ini", ".log");

    private final List<Set<String>> SUFFIXS = List.of(picSet, videoSet, documentSet);

    private final String[] PATH_ARR = {localPicPath, localVideoPath, localDocPath};
    /**
     * 对于文件的操作，应该是消息中有这个文件的地址，在前端读取时，发现这时一个文件地址
     * 那么就像后端请求这个文件，并且修改页面消息的渲染
     */

    @Override
    public String savePic(MultipartFile file) {
        if (file.isEmpty()) {
            log.error("file is empty");
            return null;
        }

        String picName = file.getOriginalFilename();

        assert picName != null;

        //获取到后缀 名字
        int poi = picName.lastIndexOf(".");

        String suffix = picName.substring(poi);

        String localPath = "";
        for(int i = 0; i < 3; i++){
            Set<String> suffixSet = SUFFIXS.get(i);
            if(suffixSet.contains(suffix)){
                localPath = PATH_ARR[i];
            }
        }

        if(localPath.isEmpty()){
            throw new RuntimeException("不支持的文件格式");
        }

        String name = picName.substring(0, poi);

        //给改为个新名字储存
        StringBuilder saveName = new StringBuilder();

        saveName.append(name).append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("-yyyy-MM-dd-HH-mm-ss"))).append(suffix);

        File dir = new File(localPath);
        //创建这个目录
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return savaToPic(dir, file, saveName);
    }

    private String savaToPic(File dir, MultipartFile file, StringBuilder saveName){
        File dest = new File(dir, saveName.toString());

        try {
            //返回的是相对路径
            file.transferTo(dest);
            //放回储存到硬盘中的url
            log.info("储存的路径 {}", localPicPath + "\\" + saveName.toString());
            //因为使用的资源映射，那么我就只需要储存图片就好了
            return saveName.toString();
        } catch (IOException e) {
            log.error("save pic error", e);
            throw new RuntimeException(e);
        }
    }

}
